package org.csu.jpetstore_users_backend_pj.controller;

import jakarta.servlet.http.HttpSession;
import org.csu.jpetstore_users_backend_pj.dto.GiteeUser;
import org.csu.jpetstore_users_backend_pj.entity.Account;
import org.csu.jpetstore_users_backend_pj.entity.Profile;
import org.csu.jpetstore_users_backend_pj.mapper.AccountMapper;
import org.csu.jpetstore_users_backend_pj.mapper.BannerDataMapper;
import org.csu.jpetstore_users_backend_pj.mapper.ProfileMapper;
import org.csu.jpetstore_users_backend_pj.service.GiteeAccessService;
import org.csu.jpetstore_users_backend_pj.service.UserService;
import org.csu.jpetstore_users_backend_pj.util.EncryptUtil;
import org.csu.jpetstore_users_backend_pj.vo.AccountVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/account")
@SessionAttributes("giteeUser")
@CrossOrigin(origins = "http://localhost:5173")
public class GiteeAccessTokenController {

    @Autowired
    private GiteeAccessService giteeAccessService;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private BannerDataMapper bannerDataMapper;
    @Autowired
    private ProfileMapper profileMapper;

    @Autowired
    private UserService userService;
    @Autowired
    private EncryptUtil encryptUtil;


    @GetMapping("/oauth/callback")
    public String handleCallback(@RequestParam("code") String code, Model model, HttpSession session) {
        Optional<String> accessTokenOpt = giteeAccessService.getToken(code);
        if (accessTokenOpt.isEmpty()) {
            return "redirect:/error?message=Gitee 认证失败";
        }
        Optional<GiteeUser> giteeUserOpt = giteeAccessService.getUser(accessTokenOpt.get());
        if (giteeUserOpt.isEmpty()) {
            return "redirect:/error?message=无法获取 Gitee 用户信息";
        }
        GiteeUser giteeUser = giteeUserOpt.get();
        String accessToken = accessTokenOpt.get();
        session.setAttribute("giteeAccessToken", accessToken); // 👈 存入
        giteeAccessService.saveAccessToken(giteeUser.getId(), accessToken);
        //  检查 Gitee 账号是否已绑定
        Account existingAccount = userService.getUserByGiteeId(giteeUser.getId());
        if (existingAccount != null) {
            AccountVO accountVO=new AccountVO();
            Profile profile=profileMapper.getProfileByUserId(existingAccount.getUserid());
            String bannerName=bannerDataMapper.getBannerNameByFavCategory(profile.getFavouriteCategoryId());
            accountVO.setAccountVO(existingAccount,profile,bannerName);

            session.setAttribute("loginAccount", accountVO); // ✅ 直接存入 HttpSession
            return "redirect:/catalog/index";  // 绑定成功，跳转到商城首页
        }
        //  Gitee 账号未绑定，存入 session，并跳转到绑定页面
        model.addAttribute("giteeUser", giteeUser);  // ✅ `@SessionAttributes` 会自动存入 session
        return "account/bindAccount"; // 显示绑定账号页面
    }

    /**
     *  处理用户绑定 Gitee 账号
     */
    @PostMapping("/oauth")
    public String bindGiteeAccount(@RequestParam("username") String username,
                                   @RequestParam("password") String password,
                                   @SessionAttribute("giteeUser") GiteeUser giteeUser, // 🔹 直接从 session 获取 GiteeUser
                                   HttpSession session, Model model) {

        Account account = userService.getById(username);
        if (account == null || !encryptUtil.verifyPwd(password,accountMapper.getPwdHashByUsername(username))) {
            model.addAttribute("error", "用户名或密码错误");
            return "account/bindAccount"; // 返回绑定页面，显示错误信息
        }
        String accessToken = (String) session.getAttribute("giteeAccessToken");
        //  绑定 Gitee 账号
        account.setGiteeId(giteeUser.getId());
        account.setGiteeNickname(giteeUser.getName());
        account.setGiteeAvatar(giteeUser.getAvatarUrl());
        account.setGiteeToken(accessToken);
        userService.updateById(account);

        AccountVO accountVO=new AccountVO();
        Profile profile=profileMapper.getProfileByUserId(username);
        String bannerName=bannerDataMapper.getBannerNameByFavCategory(profile.getFavouriteCategoryId());
        accountVO.setAccountVO(account,profile,bannerName);

        //  绑定成功，存入 session 并跳转
        session.setAttribute("loginAccount",accountVO);
        session.removeAttribute("giteeAccessToken");
        session.removeAttribute("giteeUser"); // ✅ 绑定后清除 session 数据

        return "redirect:/catalog/index";  // 绑定成功，跳转到商城首页
    }
}
